package org.su.webadapter.render;

import org.su.generalmvc.IModel;
import org.su.generalmvc.json.JsonHelper;
import org.su.generalmvc.render.IRender;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * 将action中的数据渲染为json格式数据，传递给浏览器
 * @author yangchuan
 *
 */
public class JsonRender implements IRender {
	protected static final Log logger = LogFactory.getLog(JsonRender.class);

	@Override
	public void render(IModel model, Object result, String defaultPath, ServletRequest request,
			ServletResponse response) {
		try {
			
			if(model != null && !model.isEmpty()){
				sendData(JsonHelper.createJson(model.getModel()), response);
			}else if(result != null){
				sendData(JsonHelper.createJson(result), response);
			}
		} catch (JsonGenerationException e) {
			logger.error(e);
		} catch (JsonMappingException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		}
	}

    private void sendData(Object result, ServletResponse response)
            throws IOException {
        PrintWriter out = response.getWriter();
        out.write(result.toString());
        out.flush();
        out.close();
    }


}
